package com.vueapi.controller.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Classname ZipIndexController
 * @Description TODO
 * @Created by 赵宏建
 * @Date 2023/10/4 22:25
 * @Version 1.0.0
 */
@RestController
//@RequestMapping("/zip")
public class ZipIndexController {

    @GetMapping("/folder")
    public void zipFolder(HttpServletResponse response
    ) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        File folderToZip = new File("D:\\user_data");

        if (!folderToZip.exists() || !folderToZip.isDirectory()) {
            throw new IllegalArgumentException("Invalid folder path.");
        }

        try (ZipOutputStream zipOut = new ZipOutputStream(outputStream)) {
            zipFolder(folderToZip, folderToZip.getName(), zipOut);
        }
    }

    private void zipFolder(File folderToZip, String parentFolderName, ZipOutputStream zipOut) throws IOException {
        byte[] buffer = new byte[1024];
        for (File file : folderToZip.listFiles()) {
            if (file.isDirectory()) {
                zipFolder(file, parentFolderName + "/" + file.getName(), zipOut);
                continue;
            }

            FileInputStream fis = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(parentFolderName + "/" + file.getName());
            zipOut.putNextEntry(zipEntry);

            int length;
            while ((length = fis.read(buffer)) > 0) {
                zipOut.write(buffer, 0, length);
            }

            fis.close();
        }
    }

}
